<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

		<link rel="stylesheet" href="css/bootstrap.3.4.1.css">
		<title></title>

		<script src="../libs/jquery.3.6.0.js" type="text/javascript" charset="utf-8"></script>
		
		<style type="text/css">
			
			.send-text {
				
				max-width: 500px;
			}
			
			#btn {
				min-width: 81px;
			}
			
		</style>
	</head>
	<body>


		<div class="send-text">

			<form action="" method="" class="form-inline">
				<div class="form-group">
					<input type="text" name="" id="" value="" class="form-control" />
					<button type="button" id="btn" class="btn btn-primary form-control  ">
						<!-- 发送短信 -->
						发送短信
					</button>
				</div>
				
				<div class="form-group">
					
			
				</div>
		
				

			</form>

		</div>





		<script type="text/javascript">
			// 闭包 

			// 计数器 
			// const addCounter = () => {
			// 	let count = 0;
			// 	count++;
			// 	return count;

			// }
			// // 1 1 1 1 
			// console.log(addCounter());
			// console.log(addCounter());
			// console.log(addCounter());
			// console.log(addCounter());



			// 2. 闭包实现
			// const addCounter = () => {
			// 	let count = 0;

			// 	return (
			// 		() => {
			// 			count++;
			// 			return count;
			// 		}
			// 	);
			// }
			// const closure = addCounter();
			// console.log(closure());
			// console.log(closure());
			// console.log(closure());
			// console.log(closure());
			// console.log(closure());



			//  error  1 1 1
			// console.log(addCounter()());
			// console.log(addCounter()());
			// console.log(addCounter()());



			// 3. 闭包应用 

			/*
			
			
			*/


			const addCounter = () => {
				let counter = 10;

				return (
					() => {
						if (counter <= 0) {
							counter = 10;
						}
						counter--;
						return counter;
					}
				);
			}


			const closure = addCounter();
			// console.log(closure());

			const input = document.querySelector('input');

			const btn = document.querySelector('#btn');


			input.addEventListener('input', function() {
				if (input.value) {
					btn.disable = false;
				}
			})


			btn.addEventListener('click', handleCounter);

			function handleCounter() {

				let timer = setInterval(() => {
					// console.log(closure());
					btn.textContent = closure();

					// console.log('btn.textContent: ',btn.textContent );

					let num = parseInt(btn.textContent);

					console.log('num:', num);
					if (num === 0) {
						clearInterval(timer);
						btn.textContent = '发送短信';
						input.value = '';
					}

				}, 500);

			}
		</script>
	</body>
</html>
